<template>
  <div class="mine-container">
    <!-- 个人信息展示 -->
    <el-row :gutter="20" class="info-row">
      <el-col :span="8">
        <el-card class="avatar-card" shadow="hover" style="height: 300px;">
          <div class="avatar-container">
            <el-avatar :size="120" :src="adminInfo.avatar" class="admin-avatar" @click="changeAvatar">
              <img :src="adminInfo.avatar" alt="默认头像" @click="changeAvatar"/>
            </el-avatar>
            <h3 class="admin-name">{{ adminInfo.name }}</h3>
            <p class="admin-account">{{ adminInfo.account }}</p>
            <el-tag type="success" class="admin-role">
              {{ adminInfo.role === '管理员' ? '管理员' : '超级管理员' }}
            </el-tag>
          </div>
        </el-card>
      </el-col>

      <el-col :span="16">
        <el-card class="info-card" shadow="hover" style="height: 260px;">
          <div slot="header" class="clearfix">
            <span class="info-title">基本信息</span>
            <el-button
                type="text"
                icon="el-icon-edit"
                @click="openDialog('editInfo')"
                class="edit-btn">
              编辑
            </el-button>
          </div>

          <el-descriptions :column="2" border class="info-descriptions">
            <el-descriptions-item label="账号">
              <el-tag size="small">{{ adminInfo.account }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="姓名">
              <el-tag size="small">{{ adminInfo.name }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <div class="action-buttons">
            <el-button
                type="primary"
                icon="el-icon-edit"
                @click="changeAvatar">
              修改头像
            </el-button>
            <el-button
                type="primary"
                icon="el-icon-edit"
                @click="openDialog('editInfo')">
              修改信息
            </el-button>
            <el-button
                type="warning"
                icon="el-icon-lock"
                @click="openDialog('changePwd')">
              修改密码
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改个人信息的弹出框 -->
    <el-dialog :title="dialogTitle"
               :visible.sync="dialogVisible"
               width="50%"
               :close-on-click-modal="false">
      <el-form
          :model="adminInfoForm"
          ref="adminInfoForm"
          label-width="100px"
          style="padding-right: 80px;"
          label-position="right">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账号" prop="acc">
              <el-input v-model="adminInfoForm.account" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '姓名不能为空' }]">
              <el-input v-model="adminInfoForm.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveInfo">确定</el-button>
      </span>
    </el-dialog>

    <!-- 修改密码的弹出框 -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogPwdVisible"
        width="40%"
        :close-on-click-modal="false">
      <el-form
          :model="pwdForm"
          ref="pwdForm"
          label-width="100px"
          style="padding-right: 80px;"
          label-position="right">
        <el-form-item label="旧密码" prop="oldPwd" :rules="[{ required: true, message: '旧密码不能为空' }]">
          <el-input type="password" v-model="pwdForm.oldPwd" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd" :rules="[{ required: true, message: '新密码不能为空' }]">
          <el-input type="password" v-model="pwdForm.newPwd" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPwd" :rules="[{ required: true, message: '确认密码不能为空' }]">
          <el-input type="password" v-model="pwdForm.confirmPwd" show-password></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogPwdVisible = false">取消</el-button>
        <el-button type="primary" @click="savePwd">确定</el-button>
      </span>
    </el-dialog>

    <!-- 修改头像的弹出框 -->
    <el-dialog
        title="修改头像"
        :visible.sync="dialogAvatarVisible"
        width="40%"
        :close-on-click-modal="false">
      <el-upload
          :action="$baseUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
        <i class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-dialog>

  </div>
</template>
<script>
import api from "@/api";
import {getCache} from "@/utils/useCache";

export default {
  name: "MineView",
  components: {},
  data() {
    return {
      adminInfo: {
        "account": "",
        "password": "",
        "avatar": "",
        "name": ""
      },
      dialogVisible: false,
      dialogPwdVisible: false,
      dialogAvatarVisible: false,
      dialogTitle: "",
      currentAction: "",
      adminInfoForm: {
        account: "",
        name: "",
        sex: "",
        birth: "",
        phone: "",
        address: "",
        ills: "",
        contact: "",
        bed: ""
      },
      pwdForm: {
        oldPwd: "",
        newPwd: "",
        confirmPwd: ""
      }
    };
  },
  mounted() {
    this.fetchUserInfo();
  },
  methods: {
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const cache = getCache('USERINFO');
        const response = await api.admin.adminId(cache.id);
        this.adminInfo = response.data.data;
      } catch (error) {
        this.$message.error('获取用户信息失败');
        console.error(error);
      }
    },
    // 打开对话框
    openDialog(action) {
      this.currentAction = action;
      if (action === 'editInfo') {
        this.dialogTitle = '修改个人信息';
        this.dialogVisible = true;
        this.adminInfoForm = {...this.adminInfo};
      } else if (action === 'changePwd') {
        this.dialogTitle = '修改密码';
        this.dialogPwdVisible = true;
        this.pwdForm = {
          oldPwd: "",
          newPwd: "",
          confirmPwd: ""
        };
      }
    },
    // 保存信息
    saveInfo() {
      this.$refs.adminInfoForm.validate((valid) => {
        if (valid) {
          api.admin.adminEditor(this.adminInfoForm).then(r => {
            if (r.data.code === 200) {
              this.$message.success("修改成功！");
              this.fetchUserInfo();
              this.dialogVisible = false;
            }
          }).catch(error => {
            this.$message.error("修改失败");
            console.error(error);
          });
        }
      });
    },
    // 保存密码
    savePwd() {
      this.$refs.pwdForm.validate((valid) => {
        if (valid) {
          if (this.pwdForm.newPwd !== this.pwdForm.confirmPwd) {
            this.$message.error("两次输入的新密码不一致！");
            return;
          }
          api.admin.adminChangePass(this.adminInfo.id, this.pwdForm.oldPwd, this.pwdForm.newPwd).then(r => {
            if (r.data.code === 200) {
              this.dialogPwdVisible = false;
            }
            this.$message({type: r.data.code === 200 ? 'success' : 'error', message: r.data.message, duration: 1000})
          }).catch(error => {
            this.$message.error("密码修改失败");
            console.error(error);
          });
        }
      });
    },
    // 修改头像
    changeAvatar() {
      this.dialogAvatarVisible = true;
    },
    // 头像上传成功回调
    handleAvatarSuccess(response, file) {
      console.log(file);
      this.adminInfo.avatar = response.message;
      this.dialogAvatarVisible = false;
      api.admin.adminEditor(this.adminInfo).then(r => {
        if (r.data.code === 200) {
          this.$message.success("修改成功！");
          this.fetchUserInfo();
          this.dialogVisible = false;
        }
      })
    },
    // 头像上传前校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
};
</script>
<style scoped>
.mine-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.header-content h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  margin: 5px 0 0;
  font-size: 14px;
  color: #909399;
}

.info-row {
  margin-bottom: 20px;
}

.avatar-card {
  height: 100%;
  border-radius: 8px;
  transition: all 0.3s;
}

.avatar-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.admin-avatar {
  margin-bottom: 15px;
  border: 3px solid #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.admin-name {
  margin: 10px 0 5px;
  font-size: 18px;
  color: #303133;
}

.admin-account {
  margin: 0 10px;
  font-size: 14px;
  color: #909399;
}

.admin-role {
  margin-top: 5px;
}

.info-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.info-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.info-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.edit-btn {
  float: right;
  padding: 3px 0;
  color: #409EFF;
}

.info-descriptions {
  margin-top: 10px;
}

.info-descriptions >>> .el-descriptions-item__label {
  width: 100px;
  font-weight: bold;
}

.action-buttons {
  margin-top: 40px;
  text-align: center;
}

.dialog-footer {
  text-align: center;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  color: #303133;
}

:deep(.el-upload) {
  width: 160px;
  height: 160px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  line-height: 160px;
  text-align: center;
  font-size: 40px;
}

:deep(.el-upload):hover {
  border-color: #409eff;
}

/* 响应式调整 */
@media (max-width: 1999px) {
  .info-row .el-col {
    width: 100%;
    margin-bottom: 20px;
  }

  .avatar-card {
    margin-bottom: 20px;
  }
}
</style>